import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import an49 from '@mmstudio/an000049';
import getuser from '../../atoms/getuser';

const logger = anylogger('pages/api/logo.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	img: string;
}

const key = 'logo';

/**
 * logo
 */
const handler = an48<Result>();

handler.get(async (_req, res) => {
	try {
		const db = an49();
		const tb = db<ITbsys>('sys');
		const logo = await tb.first('value').where({
			key
		});
		if (logo && logo.value) {
			res.redirect(logo.value);
		} else {
			res.redirect('/images/logo.png');
		}
	} catch (error) {
		logger.trace(error);
		res.redirect('/images/logo.png');
	}
})
	.put(async (req, res) => {
		logger.debug('body', req.body);
		const body = req.body as Message;
		try {
			const user = await getuser(req);
			if (!user || user.role !== 'admin') {
				res.json({
					ok: false,
					message: '当前用户无权限进行该操作'
				});
				return;
			}
			if (!body.img) {
				res.json({
					ok: false,
					message: '参数缺失'
				});
				return;
			}
			const db = an49();
			const tb = db<ITbsys>('sys');
			const logo = await tb.first('value').where({
				key
			});
			// update
			if (logo) {
				const tb = db<ITbsys>('sys');
				await tb.update({
					value: body.img
				})
					.where({ key });
			} else {
				// insert
				const tb = db<ITbsys>('sys');
				await tb.insert({
					key,
					value: body.img
				});
			}
			res.json({ ok: true });
		} catch (error) {
			logger.trace(error);
			res.json({
				ok: false,
				message: error.toString()
			});
		}
	});

export const config = {} as PageConfig;

export default handler;
